package com.panda.common.http.session;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * 
 * @author liuxiaobei
 * session使用示例 HttpSession httpSession = HttpSessionFactory.getHttpSession(request, response);
				  httpSession.setAttribute(AppConstants.USER_SESSION_NAME, user);
 */
@SuppressWarnings("unchecked")
public class SvSessionFactory {
	
	/**
	 * session种类
	 */
	protected static String sessionCategory = "pandaSession";
	
	/**
	 * cookie名称
	 */
	private static String cookieName = "pandaSessionCookie";
	
	/**
	 * 设置cookie一级域名,该域名的设定,直接影响cookie的生命周期.
	 * 如果请求的域名地址和该处书写的不一样,则
	 */
	public static String cookieDomain = ".panda";
	
	/**
	 * 获得session,当浏览器关闭,则该session的生命周期结束
	 * @param request
	 * @param response
	 * @return
	 */
	public static SvSession getSvSession(HttpServletRequest request, HttpServletResponse response) {
		return new SvSessionImpl(getSessionID(request, response,0));
	}
	
	/**
	 * 获得session,根据设定的maxAge为session的生命周期,单位:s,可用来做记住登录状态
	 * @param request
	 * @param response
	 * @param maxAge
	 * @return
	 */
	public static SvSession getSvSession(HttpServletRequest request, HttpServletResponse response,int maxAge) {
		return new SvSessionImpl(getSessionID(request, response,maxAge));
	}
	
	/**
	 * 获取sessionId
	 * @param request
	 * @param response
	 * @return
	 */
	private static String getSessionID(HttpServletRequest request, HttpServletResponse response,int maxAge) {
		String url = request.getRequestURL().toString();
		String sessionID = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for(int i = 0; sessionID == null && i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if(cookie.getName().equals(cookieName) && !"".equals(cookie.getValue())) {
                    sessionID = cookie.getValue();
                    return sessionID;
                }
            }
        }
        if(sessionID == null) {
            sessionID = sessionCategory + "_" + request.getSession().getId();
            Cookie httpCookie = new Cookie(cookieName,sessionID);
            httpCookie.setPath("/");
            if(url!=null){
    			if(url.indexOf(".com")>-1){
    				httpCookie.setDomain(cookieDomain+".com");
    			}
    			if(url.indexOf(".cn")>-1){
    				httpCookie.setDomain(cookieDomain+".cn");
    			}
    		}
            if(maxAge!=0){
            	httpCookie.setMaxAge(maxAge);
            }
            response.addCookie(httpCookie);
        }
        return sessionID;
	}
}
